//
//  ST_LiveBeautyController.swift
//  btvideo
//
//  Created by mac on 2021/3/18.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import SwiftyUserDefaults

class ST_LiveBeautyController: UIViewController {
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
         
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.fetch_boot_data()
        })
        
        binding()
        
        
        
    }
    
    @objc fileprivate func insert_notification_handle(){
        
//        不是已经插入了
        if let item = ST_LiveBeautyWidget.shared.my_create_room,self.data_array.first != item{
            self.data_array.insert(item, at: 0)
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
        }else{
//第一条是自己
            if self.data_array.first?.accid == ST_BTUserInfoManager.shared.current_account_info?.accid{
                self.data_array.remove(at: 0)
                
                self.pause_video()
                self.collectionView.reloadData()
            }
        }
        
        
    }
    
    @objc fileprivate func delete_notification(noti:Notification){
        
        let json = JSON(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        guard let removeIndex = data_array.firstIndex(where:({$0.accid == accid})) else{
            return
        }
        
        let index = Int(removeIndex.uInt)
        
        collectionView.performBatchUpdates({
            
            data_array.remove(at: index)
            
            collectionView.deleteItems(at: [IndexPath(row: index, section: 0)])
            
        }) { (f) in
            
            if self.data_array.count < 1{
                self.pause_video()
                self.collectionView.reloadData()
            }
            
            print("切换 显示 完毕")
            
        }
        
    }
    
    private func binding(){
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().subscribe(onNext: { f in
            print("login_status_did_changed_observable subscribe -- ST_LiveBeautyController")
             if f == true{
                 self.fetch_boot_data()
             }else{
                 self.clear_data()
             }
         }).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(ST_LiveBeautyWidget.delete_live_queue_notification, object: nil).withUnretained(self).subscribe(onNext: { own,noti in
            
            own.delete_notification(noti:noti)
            
        }).disposed(by: rx.disposeBag)
        
        
        
        
        NotificationCenter.default.rx.notification(Notification.Name.InsertMyCreateRoom, object: nil).withUnretained(self).subscribe(onNext: { own,_ in
            
            own.insert_notification_handle()
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    private func fetch_boot_data() {
        
        JVrequest(PH.roomThemeConfigApi,parameters: ["theme_type":2]) { (json) in
            
            self.header_data_array = json["data"].arrayValue.map({ ST_LiveBeautyHeaderModel(fromJson: $0) })
            
            self.header_data_array.insert(ST_LiveBeautyHeaderModel.create_recommend_data(), at: 0)
            
            self.header_data_array.first?.isSelected = true
            
            self.themeId = self.header_data_array.first?.id
            
        } failure: { (code, error) in
            
            self.toast(text: error)
        }
        
    }
    
    private func clear_data() {
        self.data_array.removeAll()
        self.pause_video()
        self.collectionView.reloadData()
    }
    
    var themeId:Int?{
        didSet{
            
            self.currentPage = 0
            self.request_data()
        }
    }
    
    fileprivate var header_data_array = [ST_LiveBeautyHeaderModel]()
    
    fileprivate var first = true
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        var param = ["page":currentPage,"size":20]
        
        if let id = themeId{
            param.updateValue(id, forKey: "theme_id")
        }
        
        JVrequest(api,parameters: param) { (json) in
            
            self.first = false
            
            let array = json["data"].arrayValue.map({ST_LiveBeautyCellModel.init(fromJson: $0)})
            
            if self.currentPage == 1{
                self.data_array = array
                
                if let item = ST_LiveBeautyWidget.shared.my_create_room{
                    self.data_array.insert(item, at: 0)
                }
                
            }else{
                self.data_array += array
            }
            
            
//            self.data_array.first?.roomCover?.url  = "http://dev-btstatic.jingniaoapps.com/DA3BCACF-4FD7-4F3E-A07C-6D3471BA9042.gif"
            
//            self.data_array.first?.roomCover?.url = "http://dev-btstatic.jingniaoapps.com/E6F64FAC-96C0-4677-9A53-7634367436E8.gif"
            
//            print("线上的人呢",json["data"])
            
            /*
            self.data_array += self.data_array
            self.data_array += self.data_array
            self.data_array += self.data_array
            */
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
            
            
            self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: 20) {[weak self] in
                
                self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        } failure: { (code, err) in
            
            self.toast(text: err)
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        }
        
    }
    
//    MARK: - Properties
    var api = ""
    
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 1
        controlLayout.minimumInteritemSpacing = 1
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 11, bottom: BTSafeAreaBottom + 49, right: 11)
        let w = (ScreenWidth - 1 - 11*2)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/168.0*190+103+4*2)
        
        controlLayout.headerReferenceSize = CGSize(width: ScreenWidth, height: 19+80)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_LiveBeautyCell.self)
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_LiveBeautyHeader.self)
        
        control.emptyDataSetSource = self
        control.emptyDataSetDelegate = self
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.white
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    
    fileprivate(set) lazy var data_array = [ST_LiveBeautyCellModel]()
    
    //    MARK:- Player View
    fileprivate lazy var playerView:ST_PeculiarityVideoPlayView = {
        let control = ST_PeculiarityVideoPlayView()
        control.isUserInteractionEnabled = false
        control.backgroundColor = .clear
        control.clipsToBounds = true
        control.isMuted = true
        control.loopPlay = true
        
        return control
    }()
    
    fileprivate var current_play_index_path:IndexPath?
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
}


//MARK: -
extension ST_LiveBeautyController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_LiveBeautyCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        

        guard let model = data_array[safe:indexPath.row] else { return  }
        
        invite_chat_action(cellModel: model)
        
        /*
        let 来源 = api == PH.fetchLiveSameCityApi ? "同城" : "推荐"
        
        MobClick.event("StartVoiceOrVideoChat", attributes: ["用户ID":model.accid,"来源":来源,"用户状态":model.state,"按钮类型":"用户头像"])
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = model.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        */
    }
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_LiveBeautyHeader.self, for: indexPath)
        
        if view.data_array.count < 1{
            view.data_array = self.header_data_array
        }
        
        view.pickIdClousre = {[weak self] id in
            self?.themeId = id
        }
        
        return view
    }
    
    
    
//    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
            scrollviewdidEndScroll(scrollView)
        
    }
    
//    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}




extension ST_LiveBeautyController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        var str = "当前没有小姐姐接受速配邀请哦\n晚点再来看看"
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo ,user.sex == .female {
            str = "小哥哥们太腼腆，主动去邀约心仪\n的小哥通话吧"
        }
        
        let attrString = NSMutableAttributedString(string: str)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor.init(hex: 0xCDD1DB)!]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_gift_empty")
    }
}


extension ST_LiveBeautyController{
    
    @objc fileprivate func invite_chat_action(cellModel:ST_LiveBeautyCellModel){
        
        if cellModel.state == 3{
            self.toast(text: "啊哦~对方正在忙哦")
            return
        }
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        
        let isVideo:Bool = cellModel.type == 2
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == cellModel.sex,let str = SCComponets.rich_text_storage_component.json["limitations"]["cot"].string,str.count > 2{

            self.toast(text: str)

            return
        }
        
        
        ST_MediaChatDispatcher.shared.inviteChat(sessionId: cellModel.accid, isVideo: isVideo,inviteDistract: "upLiveWall")
        
    }
    
}



extension ST_LiveBeautyController{
    
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for cell in collectionView.visibleCells {
            
            if determineContinueBlock(cell){
                continue
            }
            
            guard let playIdx = collectionView.indexPath(for: cell),let item_model = data_array[safe: playIdx.row],let url = item_model.roomCover?.videoUrl,url.count > 2 else { continue }
            
             if let last = foundIndex,last.item < playIdx.item{
                 continue
             }
                    
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
                        
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
            //               小于 70% 换下一个哈
            if percent < 0.8{
                continue
            }
            
           foundIndex = playIdx
                
//            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
//        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
//               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
                // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
//        print("Bug 10000-将要切换到另外一个Item :",foundIndex)
        
        return foundIndex
    }
    
    
    
                                                        
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? TianCellFollowPlayProtocol , let dataItem = data_array[safe:indexPath.item],let urlStr = dataItem.roomCover?.videoUrl ,let url = URL(string: urlStr) else{return}
        
        cell.padding(playView: playerView)
        
        playerView.play(url: url )
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
      
        playerView.stop()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
}
